<?php

namespace app\admin\controller\broadcast;
use app\common\controller\Backend;
use think\exception\DbException;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\Exception;
use think\Db;
/**
 * 照片直播原图
 *
 * @icon fa fa-circle-o
 */
class Source extends Backend
{
    /**
     * Broadcast模型对象
     * @var \app\admin\model\Broadcast
     */
    protected $model = null;
    //protected $dataLimit = true;
    protected $relationSearch = true;
    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\BroadcastImagePhoto;
        
        
    }
/**
     * 查看
     *
     * @return string|Json
     * @throws \think\Exception
     * @throws DbException
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {
           
            return $this->view->fetch();
        }
        //如果发送的来源是 Selectpage，则转发到 Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }
        [$where, $sort, $order, $offset, $limit] = $this->buildparams();

        $list = $this->model->with('admin')
            ->where($where)
            ->order($sort, $order)
            ->paginate($limit);
        $data = $list->toArray();
        foreach ($data['data'] as $key => &$value) {
            $value['broadcast_title'] = Db::name('Broadcast')->where('id',$value['broadcast_id'])->value('title');
        }
        $result = ['total' => $list->total(), 'rows' => $data['data']];
        return json($result);
    }
    /**
     * 添加
     *
     * @return string
     * @throws \think\Exception
     */
    public function add()
    {
        if (false === $this->request->isPost()) {
            $row['broadcast_id'] = $this->request->param('ids');
            $row['title'] = Db::name('Broadcast')->where('id',$row['broadcast_id'])->value('title');

            $admin =  Db::name('Admin')->alias('a')->join('__AUTH_GROUP_ACCESS__ g','g.uid = a.id')->where('g.group_id',2)->field('a.id,a.nickname,a.mobile')->select();
            $data = [];
            foreach ($admin as $key => $value) {
                $data[''.$value['id']] = $value['mobile'].'['.$value['nickname'].']';
            }
            $this->view->assign('row', $row);
            $this->view->assign('arr', $data);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }
        $result = false;
        Db::startTrans();
        try {
            $images = explode(',',$params['images']);
            if(!empty($images)){
                $photo = [];
                foreach ($images as $key => $value) {
                    $photo[] = [
                        'broadcast_id'=>$params['broadcast_id'],
                        'broadcast_image_id'=>0,
                        'image'=>$value,
                        'createtime'=>time(),
                        'updatetime'=>time(),
                        'admin_id'=>$params['admin_id'],
                        'is_source'=>1,
                        'status'=>1
                    ];
                }
                if(!empty($photo)){
                    Db::name('broadcastImagePhoto')->insertAll($photo);
                }
            }
            Db::commit();
            $result = true;
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }

    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();

        if (false === $this->request->isPost()) {
            $row['title'] = Db::name('Broadcast')->where('id',$row['broadcast_id'])->value('title');
            $admin =  Db::name('Admin')->alias('a')->join('__AUTH_GROUP_ACCESS__ g','g.uid = a.id')->where('g.group_id',2)->field('a.id,a.nickname,a.mobile')->select();
            $data = [];
            foreach ($admin as $key => $value) {
                $data[''.$value['id']] = $value['mobile'].'['.$value['nickname'].']';
            }
            $this->view->assign('row', $row);
            $this->view->assign('arr', $data);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            $result = $row->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    public function searchlist(){
       $admin =  Db::name('Admin')->alias('a')->join('__AUTH_GROUP_ACCESS__ g','g.uid = a.id')->where('g.group_id',2)->field('a.id,a.nickname,a.mobile')->select();
       $data = [];
       foreach ($admin as $key => $value) {
        $data[] = [
            'id'=>$value['id'],
            'name'=>$value['mobile'].'['.$value['nickname'].']',
        ];
        
       }
       return json($data);
    }
}
